package com.colin.orderservice10001.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.colin.common.bean.Order;
import com.colin.common.response.R;
import com.colin.orderservice10001.feign.ProductFeign;
import com.colin.orderservice10001.mapper.OrderMapper;
import com.colin.orderservice10001.service.OrderService;
import com.colin.orderservice10001.util.OrderNumUtil;
import com.netflix.discovery.converters.Auto;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public R<String> createOrder(Order order) {
        // 1. 锁库存
        R<Boolean> changeInventoryResult = productFeign.changeInventory(order.getProductId(), order.getProductCount());
        if (!changeInventoryResult.getData()) {
            return R.error();
        }

        // 2. 创建订单
        long currentTime = System.currentTimeMillis();

        Long pkGenerate = stringRedisTemplate.opsForValue().increment("pkGenerate");
        String orderNum = OrderNumUtil.getOrderNum("ORDER", currentTime, StpUtil.getLoginIdAsInt(), pkGenerate);

        order.setOrderNum(orderNum);
        order.setOrderStatus(0);

        Timestamp currentTimestamp = new Timestamp(currentTime);

        order.setCreateTime(currentTimestamp);
        order.setUpdateTime(currentTimestamp);
        order.setUserId(StpUtil.getLoginIdAsInt());

        if (!orderMapper.insertOrder(order)) {
            return R.error();
        }

        // 3. 超时关单处理
        rabbitTemplate.convertAndSend("order.delay.close.queue", orderNum);
        return R.ok(orderNum);
    }

    @Override
    public R<Order> getOrder(String orderNum) {
        return R.ok(orderMapper.selectOrder(orderNum));
    }

    @Override
    public R<Boolean> changeOrderStatus(String orderNum, Integer orderStatus) {
        return R.ok(orderMapper.updateStatus(orderNum, orderStatus));
    }
}
